<template>
  <el-dialog
    :title="dialogTitle"
    v-model="visible"
    width="1000px"
    append-to-body
    @close="handleClose"
  >
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      label-width="auto"
      class="dense-form"
    >
      <el-form-item label="手机号" prop="phone" class="form-item-compact" label-width="60px">
        <el-input
          v-model="queryParams.phone"
          placeholder="请输入"
          clearable
          @keyup.enter="handleQuery"
          style="width: 150px"
        />
      </el-form-item>

      <el-form-item label="姓名" prop="name" class="form-item-compact" label-width="60px">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入"
          clearable
          @keyup.enter="handleQuery"
          style="width: 150px"
        />
      </el-form-item>

      <el-form-item :label="contractNumberLabel" prop="contractNumber" class="form-item-compact" label-width="120px">
        <el-input
          v-model="queryParams.contractNumber"
          placeholder="请输入"
          clearable
          @keyup.enter="handleQuery"
          style="width: 150px"
        />
      </el-form-item>

      <el-form-item class="form-item-compact ml-10px">
        <el-button type="primary" @click="handleQuery">查询</el-button>
        <el-button @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table
      ref="tableRef"
      v-loading="loading"
      :data="recipientList"
      @selection-change="handleSelectionChange"
      @select-all="handleTableSelectAll"
      style="margin-top: 20px"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="接收人" align="center" prop="name" />
      <el-table-column label="手机号" align="center" prop="phone" />
      <el-table-column :label="contractNumberLabel" align="center" prop="contractNumber" />
    </el-table>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup name="RecipientSelectorDialog">
import { ref, reactive, computed, watch, getCurrentInstance, nextTick } from 'vue'
import { getEffectiveHomeownersList, getEffectiveTenantList } from '@/api/fang/common'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  recipientType: {
    type: Number,
    default: 1 // 1-租客, 2-房东
  },
  selectedList: {
    type: Array,
    default: () => []
  },
  selectAllFlag: {
    type: Boolean,
    default: false
  }
})

watch(
  () => props.selectedList,
  () => {
    if (visible.value && !selectAll.value) {
      applySelection()
    }
  },
  { deep: true }
)

watch(
  () => props.selectAllFlag,
  (val) => {
    if (visible.value) {
      selectAll.value = val
      if (val) {
        selectedRecipients.value = []
        tableRef.value?.clearSelection()
      } else {
        applySelection()
      }
    }
  }
)

function handleSelectAllChange(val) {
  if (val) {
    selectedRecipients.value = []
    tableRef.value?.clearSelection()
  } else {
    applySelection()
  }
}

function selectableRow() {
  return !selectAll.value
}

function applySelection() {
  nextTick(() => {
    if (!tableRef.value) return
    tableRef.value.clearSelection()
    if (selectAll.value) return
    const matchedRows = []
    recipientList.value.forEach(row => {
      if (isRowPreSelected(row)) {
        tableRef.value.toggleRowSelection(row, true)
        matchedRows.push(row)
      }
    })
    selectedRecipients.value = matchedRows
  })
}

const emit = defineEmits(['update:modelValue', 'confirm'])

const visible = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val)
})

const recipientList = ref([])
const selectedRecipients = ref([])
const loading = ref(false)
const selectAll = ref(false)
const tableRef = ref(null)

const queryParams = reactive({
  phone: null,
  name: null,
  contractNumber: null
})

const { proxy } = getCurrentInstance()

// 根据接收人类型动态显示弹窗标题
const dialogTitle = computed(() => {
  return props.recipientType === 1 ? '请选择租客' : '请选择房东'
})

// 根据接收人类型动态显示合同编号标签
const contractNumberLabel = computed(() => {
  return props.recipientType === 1 ? '租赁合同编号' : '委托合同编号'
})

/** 查询接收人列表 */
function getList() {
  loading.value = true
  const params = {
    phone: queryParams.phone || undefined,
    name: queryParams.name || undefined,
    contractNumber: queryParams.contractNumber || undefined
  }
  
  // 根据接收人类型调用不同的接口
  const apiCall = props.recipientType === 1 
    ? getEffectiveTenantList(params)
    : getEffectiveHomeownersList(params)
  
  apiCall.then(response => {
    if (response.code === 200) {
      recipientList.value = response.rows || []
      applySelection()
    } else {
      proxy.$modal.msgError(response.msg || '查询失败')
      recipientList.value = []
    }
  }).catch(error => {
    console.error('查询接收人列表失败:', error)
    proxy.$modal.msgError('查询失败')
    recipientList.value = []
  }).finally(() => {
    loading.value = false
  })
}

/** 搜索按钮操作 */
function handleQuery() {
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm('queryRef')
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  selectedRecipients.value = selection
  updateSelectAllState(selection)
}

function handleTableSelectAll(selection) {
  selectedRecipients.value = selection
  updateSelectAllState(selection)
}

/** 确定按钮操作 */
function handleConfirm() {
  emit('confirm', {
    recipients: selectedRecipients.value,
    selectAll: selectAll.value,
    recipientType: props.recipientType
  })
  handleClose()
}

/** 关闭弹窗 */
function handleClose() {
  visible.value = false
  selectedRecipients.value = []
  proxy.resetForm('queryRef')
  selectAll.value = false
}

// 监听弹窗打开
watch(visible, (val) => {
  if (val) {
    selectAll.value = props.selectAllFlag
    selectedRecipients.value = []
    getList()
  }
})

watch(
  () => props.selectedList,
  () => {
    if (visible.value) {
      applySelectionFromProps()
    }
  },
  { deep: true }
)

watch(
  () => props.selectAllFlag,
  (val) => {
    if (visible.value) {
      selectAll.value = val
      applySelectionFromProps()
    }
  }
)

function applySelectionFromProps() {
  nextTick(() => {
    if (!tableRef.value) return
    tableRef.value.clearSelection()
    if (recipientList.value.length === 0) return

    if (selectAll.value) {
      tableRef.value.toggleAllSelection()
      selectedRecipients.value = [...recipientList.value]
      return
    }

    const matchedRows = []
    recipientList.value.forEach(row => {
      if (isRowPreSelected(row)) {
        tableRef.value.toggleRowSelection(row, true)
        matchedRows.push(row)
      }
    })
    selectedRecipients.value = matchedRows
  })
}

function isRowPreSelected(row) {
  if (!Array.isArray(props.selectedList)) return false
  return props.selectedList.some(item => {
    if (row.id && item.targetId) return row.id === item.targetId
    if (row.homeownersId && item.homeownersId) return row.homeownersId === item.homeownersId
    if (row.leaseContractId && item.leaseContractId) return row.leaseContractId === item.leaseContractId
    return item.name === row.name && item.phone === row.phone
  })
}

function updateSelectAllState(selection) {
  selectAll.value =
    recipientList.value.length > 0 &&
    selection.length === recipientList.value.length
}
</script>

<style scoped>
.dense-form {
  display: flex;
  flex-wrap: nowrap;
  align-items: flex-start;
}

.dense-form :deep(.el-form-item) {
  margin-bottom: 0;
  margin-right: 12px;
  flex-shrink: 0;
}

.dense-form :deep(.el-form-item__label) {
  padding-right: 6px;
  white-space: nowrap;
}

.dense-form :deep(.form-item-compact) {
  margin-bottom: 0;
}
</style>

